package com.hhkj.admin.bank.model.res;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hhkj.admin.bank.common.cont.BankConst;
import com.hhkj.admin.bank.common.cont.QuestionOrderRuleConst;
import com.hhkj.admin.bank.domain.BankRule;
import com.hhkj.admin.bank.model.dopo.BankPo;
import com.hhkj.admin.question.domain.Question;
import com.hhkj.admin.question.model.res.QuestionRes;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * BankRes
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/6/13 10:30
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class BankRes extends BankPo
{
    /** 题目分组列表信息 */
    private List<QuestionRes> questionGroupList;

    public List<QuestionRes> getQuestionGroupList()
    {
        return questionGroupList;
    }

    public void orderPractiseQuestionList()
    {
        if (CollectionUtil.isEmpty(this.questionGroupList)
                || !BankConst.Type.PRACTISE.getCode().equals(this.getTypeCode())
                || ObjectUtil.isNull(this.getRule())
                || ObjectUtil.isNull(this.getRule().getPracticeOrderRule())) {
            return;
        }
        BankRule bankRule = this.getRule();
        if (QuestionOrderRuleConst.Type.MANUAL_SORT_TYPE.getCode().equals(bankRule.getPracticeOrderRule().getTypeCode())
                && CollectionUtil.isNotEmpty(bankRule.getPracticeOrderRule().getQuestionTypeCodeList())) {

            List<QuestionRes> newQuestionGroupList = new ArrayList<>();
            Map<String, List<QuestionRes>> questionListGroupByTypeCode = this.questionGroupList.stream()
                    .collect(Collectors.groupingBy(QuestionRes::getTypeCode));
            for (String questionTypeCode : bankRule.getPracticeOrderRule().getQuestionTypeCodeList()) {
                if (questionListGroupByTypeCode.containsKey(questionTypeCode)) {
                    newQuestionGroupList.addAll(questionListGroupByTypeCode.get(questionTypeCode));
                }
            }
            this.questionGroupList = newQuestionGroupList;
        }
    }

    public void setQuestionGroupList(List<QuestionRes> questionGroupList)
    {
        this.questionGroupList = questionGroupList;
        Map<String, Integer> typeAmountMap = questionGroupList.stream()
                .collect(Collectors.groupingBy(Question::getTypeCode,
                        Collectors.collectingAndThen(Collectors.toList(), List::size)));
        this.setTypeAmountConf(typeAmountMap);
    }
}
